The -f option must be last and when the -V option is recognized the rest of the command line is ignored.
A pattern can be:
Statements are terminated by newlines, semi-colons or both. Groups of statements such as actions or loop bodies are blocked via { ... } as in C. The last statement in a block doesn't need a terminator. Blank lines have no meaning; an empty statement is terminated with a semi-colon. Long statements can be continued with a backslash, \. A statement can be broken without a backslash after a comma, left brace, &&, ||, do, else, the right parenthesis of an if, while or for statement, and the right parenthesis of a function definition. A comment starts with # and extends to, but does not include the end of line.
The following statements control program flow inside blocks.
if ( expr ) statement
if ( expr ) statement else statement
while ( expr ) statement
do statement while ( expr )
for ( opt_expr ; opt_expr ; opt_expr ) statement
for ( var in array ) statement
continue
break
String constants are enclosed in double quotes.
"This is a string with a newline at the end.\n"
Strings can be continued across a line by escaping (\) the newline. The following escape sequences are recognized.
\\ \ \" " \a alert, ascii 7 \b backspace, ascii 8 \t tab, ascii 9 \n newline, ascii 10 \v vertical tab, ascii 11 \f formfeed, ascii 12 \r carriage return, ascii 13 \ddd 1, 2 or 3 octal digits for ascii ddd \xhh 1 or 2 hex digits for ascii hhIf you escape any other character \c, you get \c, i.e., mawk ignores the escape.
There are really three basic data types; the third is number and string which has both a numeric value and a string value at the same time. User defined variables come into existence when first referenced and are initialized to null, a number and string value which has numeric value 0 and string value "". Non-trivial number and string typed data come from input and are typically stored in fields. (See section 4).
The type of an expression is determined by its context and automatic type conversion occurs if needed. For example, to evaluate the statements
y = x + 2 ; z = x "hello"The value stored in variable y will be typed numeric. If x is not numeric, the value taken from x is converted to numeric before it is added to 2 and stored in y. The value stored in variable z will be typed string, and the value of x will be converted to string if necessary and concatenated with "hello". (Of course, the value and type stored in x is not changed by any conversions.) A string expression is converted to numeric using its longest numeric prefix as with atof(3). A numeric expression is converted to string by replacing expr with sprintf( OFMT, expr). Sprintf() is an AWK built-in that duplicates the functionality of sprintf(3). Explicit type conversions can be forced, expr "" is string and expr+0 is numeric.
To evaluate, expr1 rel-op expr2, if both operands are numeric or number and string then the comparison is numeric; if both operands are string the comparison is string; if one operand is string, the non-string operand is converted and the comparison is string. The result is numeric, 1 or 0. In boolean contexts such as, if ( expr ) statement, a string expression evaluates true if and only if it is not the empty string ""; otherwise if and only if not numerically zero.
expr ~ /r/is an AWK expression that evaluates to 1 if expr "matches" r, which means a substring of expr is in the set of strings defined by r. With no match the expression evaluates to 0; replacing ~ with the "not match" operator, !~ , reverses the meaning. As a pattern,
/r/ { action } is the same as $0 ~ /r/ { action }and for each input record that matches r, action is executed.
AWK uses extended regular expressions as with egrep(1). The regular expression metacharacters, i.e., those with special meaning in regular expressions are
^ $ . [ ] | ( ) * + ?Regular expressions are built up from characters as follows:
Regular expressions are built up from other regular expressions as follows:
The increasing precedence of operators is alternation, concatenation and unary (*, + or ?).
For example,
/^[_a-zA-Z][_a-zA-Z0-9]*$/ and /^[-+]?([0-9]+\.?|\.[0-9])[0-9]*([eE][-+]?[0-9]+)?$/are matched by AWK identifiers and AWK numeric constants respectively. Note that . has to be escaped to be recognized as a decimal point, and that metacharacters are not special inside character classes.
Any expression can be used on the right hand side of the ~ or !~ operators or passed to a built-in that expects a regular expression. If needed, it is converted to string and then interpreted as a regular expression. For example,
BEGIN { identifier = "[_a-zA-Z][_a-zA-Z0-9]*" } $0 ~ "^" identifierprints all lines that start with an AWK identifier.
mawk recognizes the empty regular expression, //, which matches the empty string and hence is matched by any string at the front, back and between every character. For example,
echo abc | mawk { gsub(//, "X") ; print } XaXbXcX
Assignment to $0 causes the fields and NF to be recomputed. Assignment to NF or to a field causes $0 to be reconstructed using OFS. Assignment to a field with index greater than NF, increases NF and causes $0 to be reconstructed.
Data input stored in fields is string, unless the entire field has numeric form and then the type is number and string. For example,
echo 24 24E | mawk '{ print($1>100, $1>"100", $2>100, $2>"100") }' 0 1 1 1
$0 and $2 are string and $1 is number and string. The first comparison is numeric, the second is string, the third is string (100 is converted to "100"), and the last is string.
The expression syntax is similar to C. Primary expressions are numeric constants, string constants, variables, fields, arrays and functions. The identifier for a variable, array or function can be a sequence of letters, digits and underscores, that does not start with a digit. Variables are not declared; they exist when first referenced and are initialized to null.
New expressions are composed with the following operators in order of increasing precedence.
assignment = += -= *= /= %= ^= conditional ? : logical or || logical and && array membership in matching ~ !~ relational < > <= >= == != concatenation (no explicit operator) add ops + - mul ops * / % unary + - logical not ! exponentiation ^ inc and dec ++ -- (both post and pre) field $
There is a form of the for statement that loops over each element of an array.
for ( var in array ) statementsets var to each element of array and executes statement. The order of execution is not defined.
The statement, delete array[expr], causes array[expr] not to exist.
Multidimensional arrays are synthesized with concatenation using the built-in variable SUBSEP. array[expr1,expr2] is equivalent to array[expr1 SUBSEP expr2]. Testing for a multidimensional element uses a parenthesized index, such as
if ( (i, j) in A ) print A[i, j]
The following variables are built-in and initialized before program execution.
Arithmetic functions
atan2(y,x) Arctan of y/x between -pi and pi. cos(x) Cosine function, x in radians. exp(x) Exponential function. int(x) Returns x truncated towards zero. log(x) Natural logarithm. rand() Returns a random number between zero and one. sin(x) Sine function, x in radians. sqrt(x) Returns square root of x.
The output of print and printf can be redirected to a file or command by appending > file, >> file or | command to the end of the print statement. Redirection opens file or command only once, subsequent redirections append to the already open stream. The argument list to print or printf can optionally be enclosed in parentheses.
The input function getline has the following variations.
Getline returns 0 on end-of-file, -1 on error, otherwise 1. Command is executed by /bin/sh.
The function close(expr) closes the file or pipe associated with expr. Close returns 0 or -1 if expr is not associated with an open stream. Close() is used to reread a file or command, make sure the other end of an output pipe is finished or conserve file resources.
The function system(expr) uses /bin/sh to execute expr and returns the exit status of the command expr.
function name( args ) { statements }The function body can contain a return statement
return opt_exprA return statement is not required. Function calls may be nested or recursive. Functions are passed expressions by value and arrays by reference. Extra arguments serve as local variables and are initialized to null. For example, csplit(s,A) puts each character of s into array A and returns the length of s.
function csplit(s, A, n, i) { n = length(s) for( i = 1 ; i <= n ; i++ ) A[i] = substr(s, i, 1) return n }Putting extra space between passed arguments and local variables is conventional. Functions can be referenced before they are defined, but the function name and the '(' of the arguments must touch to avoid confusion with concatenation.
Split(expr,A,sep) works as follows:
Splitting records into fields works the same except the pieces are loaded into $1, $2,..., $NF. If $0 is empty, NF is set to 0 and all $i to "".
mawk splits files into records by the same algorithm, but with the slight difference that RS is really a terminator instead of a separator. (ORS is really a terminator too).
E.g., if FS = ":+" and $0 = "a::b:" , then NF = 3 and $1 = "a", $2 = "b" and $3 = "", but if "a::b:" is the contents of an input file and RS = ":+", then there are two records "a" and "b".
For example, if a file is "a b\nc\n\n", RS = "\n\n+" and FS = " ", then there is one record "a b\nc" with three fields "a", "b" and "c". Changing FS = "\n", gives two fields "a b" and "c"; changing FS = "", gives one field identical to the record.
If you want lines with spaces or tabs to be considered blank, set RS = "\n([ \t]*\n)+". For compatibility with other awks, setting RS = "" has the same effect on determining records as RS = "\n\n+". (This interpretation makes mawk picky that the input not start with blank lines and that the last record is fully terminated with at least two newlines.)
Most of the time when you change RS for multi-line records, you will also want to change ORS to "\n\n" so the record spacing is preserved on output.
mawk -f prog v=1 A t=hello BARGC = 5 with ARGV[0] = "mawk", ARGV[1] = "v=1", ARGV[2] = "A", ARGV[3] = "t=hello" and ARGV[4] = "B". Next, each BEGIN block is executed in order. If the program consists entirely of BEGIN blocks, then execution terminates, else an input stream is opened and execution continues. If ARGC equals 1, the input stream is set to stdin, else the command line arguments ARGV[1] ... ARGV[ARGC-1] are examined for a file argument.
The command line arguments divide into three sets: file arguments, assignment arguments and empty strings "". An assignment has the form var=string. When an ARGV[i] is examined as a possible file argument, if it is empty it is skipped; if it is an assignment argument, the assignment to var takes place and i skips to the next argument; else ARGV[i] is opened for input. If it fails to open, execution terminates with exit code 1. If no command line argument is a file argument, then input comes from stdin. Getline in a BEGIN action opens input. "-" as a file argument denotes stdin.
Once an input stream is open, each input record is tested against each pattern, and if it matches, the associated action is executed. An expression pattern matches if it is boolean true (see the end of section 2). A regular expression pattern matches if $0 matches the regular expression. A BEGIN pattern matches before any input has been read, and an END pattern matches after all input has been read. A range pattern, pat1,pat2 , matches every record between the match of pat1 and the match pat2 inclusively.
When end of file occurs on the input stream, the remaining command line arguments are examined for a file argument, and if there is one it is opened, else the END pattern is considered matched and all END actions are executed.
In the example, the assignment v=1 takes place after the BEGIN actions are executed, and the data placed in v is typed number and string. Input is then read from file A. On end of file A, t is set to the string "hello", and B is opened for input. On end of file B, the END actions are executed.
Program flow at the pattern {action} level can be changed with the
next and exit opt_exprstatements. A next statement causes the next input record to be read and pattern testing to restart with the first pattern {action} pair in the program. An exit statement causes immediate execution of the END actions or program termination if there are none or if the exit occurs in an END action. The opt_expr sets the exit value of the program unless overridden by a later exit or subsequent error.
1. emulate cat. { print } 2. emulate wc. { chars += length($0) + 1 # add one for the \n words += NF } END{ print NR, words, chars } 3. count the number of unique "real words". BEGIN { FS = "[^A-Za-z]+" } { for(i = 1 ; i <= NF ; i++) word[$i] = "" } END { delete word[""] for ( i in word ) cnt++ print cnt }4. sum the second field of every record based on the first field.
$1 ~ /credit|gain/ { sum += $2 } $1 ~ /debit|loss/ { sum -= $2 } END { print sum } 5. sort a file, comparing as string { line[NR] = $0 "" } # make sure of comparison type # in case some lines look numeric END { isort(line, NR) for(i = 1 ; i <= NR ; i++) print line[i] } #insertion sort of A[1..n] function isort( A, n, i, j, hold) { for( i = 2 ; i <= n ; i++) { hold = A[j = i] while ( A[j-1] > hold ) { j-- ; A[j+1] = A[j] } A[j] = hold } # sentinel A[0] = "" will be created if needed }
With mawk, the following are all equivalent,
x ~ /a\+b/ x ~ "a\+b" x ~ "a\\+b"The strings get scanned twice, once as string and once as regular expression. On the string scan, mawk ignores the escape on non-escape characters while the AWK book advocates \c be recognized as c which necessitates the double escaping of meta-characters in strings. For programs that must run under a variety of awks, the more portable but less readable, double escape should be used.
POSIX AWK is oriented to operate on files a line at a time. RS can be changed from "\n" to another single character, but it is hard to find any use for this --- there are no examples in the AWK book. By convention, RS = "", makes one or more blank lines separate records, allowing multi-line records. When RS = "", "\n" is always a field separator regardless of the value in FS.
mawk, on the other hand, allows RS to be a regular expression. When "\n" appears in records, it is treated as space, and FS always determines fields. RS = "" is treated the same as RS = "\n\n+".
Removing the line at a time paradigm can make some programs simplier and can often improve performance. For example, redoing example 3 from above,
BEGIN { RS = "[^A-Za-z]+" } { word[ $0 ] = "" } END { delete word[ "" ] for( i in word ) cnt++ print cnt }counts the number of unique words by making each word a record. On moderate size files, mawk executes twice as fast, because of the simplified inner loop.
The following program replaces each comment by a single space in a C program file,
BEGIN { RS = "/\*([^*]|\*+[^/*])*\*+/" # comment is record separator ORS = " " getline hold } { print hold ; hold = $0 } END { printf "%s" , hold }Buffering one record is needed to avoid terminating the last record with a space.
Finally, here is how mawk handles exceptional cases not discussed in the AWK book or the POSIX draft. It is unsafe to assume consistency across awks and safe to skip to the next section.
Aho, Kernighan and Weinberger, The AWK Programming Language, Addison-Wesley Publishing, 1988, (the AWK book), defines the language, opening with a tutorial and advancing to many interesting programs that delve into issues of software design and analysis relevant to programming in any language.
The GAWK Manual, The Free Software Foundation, 1991, is a tutorial and language reference that does not attempt the depth of the AWK book and assumes the reader may be a novice programmer. The section on AWK arrays is excellent. It also discusses POSIX requirements for AWK.